<?php
/**
 * jishupu-cms
 * @Author:技术铺<jishupu@qq.com>
 * @Date: 2022/4/2
 */

namespace App\Console\Commands;

use App\Services\CacheService;
use App\Services\RouteService;
use Carbon\Carbon;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Redis;

/**
 * redis订阅命令
 * Class RedisPublishRouteSubscribe
 * @package App\Console\Commands
 */
class RedisSubscribe extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'redis:subscribe';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '执行redis订阅';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        $channels = [
            'website-route-cache-channel', // 更新路由频道
            'website-cache-channel' // 更新前台应用缓存、路由缓存频道
        ];
        $redis_pubsub_prefix = config('database.redis.pubsub.options.prefix');
        // 订阅多频道
        ini_set('default_socket_timeout', -1);
        Redis::connection('pubsub')->subscribe($channels, function ($message, $channel) use ($redis_pubsub_prefix) {
            switch ($channel) {
                case $redis_pubsub_prefix . 'website-route-cache-channel':
                    // 更新前台路由缓存
                    RouteService::updateRouteCache();
                    break;
                case $redis_pubsub_prefix . 'website-cache-channel':
                    // 更新前台应用缓存、路由缓存
                    CacheService::clear();
                    RouteService::updateRouteCache();
                    break;
            }
            echo $message . Carbon::now() . "\n";
        });
        return 0;
    }
}
